package com.lxyk.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.druid.util.StringUtils;
import com.lxyk.pojo.Account;
import com.lxyk.pojo.Result;
import com.lxyk.service.AccountService;
import com.lxyk.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@Slf4j
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /*1.调用业务成 login方法
    * 2.如果用户名密码正确 登陆成功 跳转到后台首页
    * 3.否则不跳转
    * */

    @PostMapping("/login")
    public String loginAccount(String userName, String userPwd, Model model, HttpSession session){
        boolean result = accountService.login(userName, userPwd);
        if (result){
            //登陆成功 进入首页  把用户存到session
            session.setAttribute("currentUser",userName);
            return "waterMainMenu";
        }else {
            model.addAttribute("loginFail","用户名或密码错误");

            return "index";
        }

    }
    /**
     * 手机登录
     * @param phone
     * @param code
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/loginPhone")
    public String login(String phone,String code,HttpSession session,Model model){
        String redisCode = redisTemplate.opsForValue().get(phone);
        log.info(redisCode);
        if (redisCode != null && phone != null){
            if (redisCode.equals(code)){
                session.setAttribute("currentUser",phone);
                //清除redis的验证码
                redisTemplate.delete(phone);
                //登录成功
                return "waterMainMenu";
            }
            return "index";
        }else {
            model.addAttribute("msg","验证码错误");
            return "index";
        }
    }

    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    @ResponseBody
    public Result sendCode(@PathVariable String phone){
        // 从redis获取验证码  如果获取到  返回ok
        // key 手机号  value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果从redis获取不到
        //生产验证码，通过整合短信服务进行发送
        code = RandomUtil.getSixBitRandom();
        //调用service方法 通过整合阿里云短信服务进行发送
        boolean isSend = accountService.send(phone, code);
        //生产验证码放到redis
        if(isSend){
            redisTemplate.opsForValue().set(phone,code);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }
    //跳转到注册页面 register
    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    //用户注册
    @RequestMapping("/reg")
    public String reg(String userName,String userPwd,String password,
                      String userEmail,String userMobile,Model model
    ){
        //检查用户名 是否唯一
        Account account = accountService.selectByName(userName);
        if (account != null){
            model.addAttribute("msg","当前账户已存在");
            return "register";
        }
        //密码需要加密
        String newUserPwd = DigestUtil.md5Hex(userPwd);
        String newPassword = DigestUtil.md5Hex(password);
        if (!newUserPwd.equals(newPassword)){
            model.addAttribute("msg","两次密码不一致");
            return "register";
        }
        //执行用户注册
        accountService.addAccount(userName,userPwd,password,userEmail,userMobile);
        //注册成功跳转到登录页面
        return "index";
    }
    /*
     * 返回主页面
     * */
    @RequestMapping("/hello")
    public String hello(){
        return "waterMainMenu";
    }
    //跳转到修改密码页面
    @RequestMapping("/pwd")
    public String pwd(HttpSession session,Model model){
        model.addAttribute("uName",session.getAttribute("currentUser"));
        return "modifypwd";
    }
    @RequestMapping(value = "/pwdUp",method = RequestMethod.POST)
    public String pwdUp(String userPwd,String newPwd,Model model,HttpSession se){
        String userName = (String) se.getAttribute("currentUser");
        boolean login = accountService.login(userName, userPwd);
        if (login){
            Account account1 = new Account();
            account1.setUserName(userName);
            String encodePwd = DigestUtil.md5Hex(newPwd);

            account1.setUserPwd(encodePwd);
            boolean b = accountService.pwdUser(account1);
            if (b){
                return "index";
            }else {
                model.addAttribute("loginFail","修改失败");
                model.addAttribute("uName",se.getAttribute("currentUser"));
                return "modifypwd";
            }
        }else {
            model.addAttribute("loginFail","用户名或密码错误");
            model.addAttribute("uName",se.getAttribute("currentUser"));
            return "modifypwd";
        }
    }

}
